package com.jason.basicandroid.contentprovider;

import com.jason.basicandroid.contentprovider.BookProviderMetaData.BookTableMetaData;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class BookEditor extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.book_editor);

    	Long id = getIntent().getLongExtra(BookTableMetaData.BOOK_ID, -1);
    	if(id >= 0) {
    		Uri theBook = Uri.withAppendedPath(BookTableMetaData.CONTENT_ITEM_URI, id.toString());
    		Cursor c = managedQuery(theBook, null, null, null, null);
    		
    		if(c.moveToFirst()) {
    			String strName = c.getString(c.getColumnIndex(BookTableMetaData.BOOK_NAME));
    			((EditText)findViewById(R.id.txName)).setText(strName);
    			String strAuthor = c.getString(c.getColumnIndex(BookTableMetaData.BOOK_AUTHOR));
    			((EditText)findViewById(R.id.txAuthor)).setText(strAuthor);
    			String strISBN = c.getString(c.getColumnIndex(BookTableMetaData.BOOK_ISBN));
    			((EditText)findViewById(R.id.txISBN)).setText(strISBN);
    		}
    	}
    }

    public void onBtnClick(View v) {
        Intent backIntent = new Intent();

        switch(v.getId()) {
        case R.id.btnOK:
        	Long id = getIntent().getLongExtra(BookTableMetaData.BOOK_ID, -1);
        	String strName = ((EditText)findViewById(R.id.txName)).getText().toString();
        	String strAuthor = ((EditText)findViewById(R.id.txAuthor)).getText().toString();
        	String strISBN = ((EditText)findViewById(R.id.txISBN)).getText().toString();

        	backIntent.putExtra(BookTableMetaData.BOOK_ID, id);
        	backIntent.putExtra(BookTableMetaData.BOOK_NAME, strName);
        	backIntent.putExtra(BookTableMetaData.BOOK_AUTHOR, strAuthor);
        	backIntent.putExtra(BookTableMetaData.BOOK_ISBN, strISBN);
        	
            setResult(RESULT_OK, backIntent);
        	
            break;

        case R.id.btnCancel:
            setResult(RESULT_CANCELED, backIntent);
                
            break;
 
	    default:
	    	break;
        }
                
        finish();
    }
}


